<?php
$isReloadable = true;
require_once("../../../pers/inc.config.php");
require_once('../../_inc/inc.session.php');
require_once('../../_inc/funct.html.php');

$sql_sel = "SELECT d.*" .
		" FROM rgl_tabelle d " .
		" WHERE d.id_tabella = ".intval(reqVar('id'));
$objDB->query($sql_sel,'selRecDom');
$acRecDom = $objDB->fetch('selRecDom');
if (!$acRecDom) {
	header("location: tabelleList.php?msgpag=".urlencode("tabelleView - manca id").
		"&".$sXSNQS);
	exit();
}
if (reqVar('azione')=='importa') {
	$msgPag .= importaDomVal();
}
if (reqVar('azione')=='elimina') {
	$msgPag .= eliminaDom();
}
$aWhere = array(" id_tabella = ".intval(reqVar('id')));
if (reqVar('pagifilt')!='') {
	$aWhere[] = " (v.chiave LIKE '%".addslashes(reqVar('pagifilt'))."%' "
		." OR v.c01 LIKE '%".addslashes(reqVar('pagifilt'))."%' "
		." OR v.c02 LIKE '%".addslashes(reqVar('pagifilt'))."%' "
		." OR v.c03 LIKE '%".addslashes(reqVar('pagifilt'))."%' "
		." OR v.c04 LIKE '%".addslashes(reqVar('pagifilt'))."%' "
		." OR v.c05 LIKE '%".addslashes(reqVar('pagifilt'))."%' " 
		." OR v.c06 LIKE '%".addslashes(reqVar('pagifilt'))."%' " 
		." OR v.c07 LIKE '%".addslashes(reqVar('pagifilt'))."%' " 
		." OR v.c08 LIKE '%".addslashes(reqVar('pagifilt'))."%' " 
		.") ";
}
$sWhere = (count($aWhere)==0)? "":" WHERE ".implode(" AND ",$aWhere);
$sql_sel = "SELECT count(*) AS num_rec " .
		" FROM rgl_tabelle_val v " .$sWhere;
//dbg_($sql_sel);
$objDB->query($sql_sel,'selRecVal');
$acRec = $objDB->fetch('selRecVal');
$numRec = $acRec['num_rec'];
$link = $_SERVER['PHP_SELF']."?id=".reqVar('id')."&".$sXSNQS;
$startOffset = 0;
$endOffset = 0;
$sFiltro = rglGetFiltro($link);
$sPaginaz = rglGetPaginaz($link, $numRec, $startOffset, $endOffset);

$sql_sel = "SELECT v.*" .
		" FROM rgl_tabelle_val v " .$sWhere.
		" ORDER BY v.chiave ".
		" LIMIT ".$startOffset.",".($endOffset-$startOffset);
$objDB->query($sql_sel,'selRecVal');
//dbg_($sql_sel);
$cmdL1 = "";
$cmdL1 .= "<a class=\"cmd1\" href=\"tabelleExp.php?id=".reqVar('id')."&$sXSNQS\">esporta</a>"; 
$cmdL1 .= "&nbsp;&nbsp;&nbsp;";
$cmdR1 = "";
if (true) {
	$cmdR1 .= "&nbsp;&nbsp;&nbsp;";
	$cmdR1 .= "<a class=\"cmd1\" href=\"tabelleMod.php?id=".reqVar('id')."&$sXSNQS\">modifica</a>";
	$cmdR1 .= "&nbsp;&nbsp;&nbsp;";
	$cmdR1 .= "<a class=\"cmd1\" href=\"#\" onClick=\"confElimina();\">elimina</a>";
}
$cmdR1 .= cmdTorna(); 

$cmdL = "";

$cmdR = "";
if (true) {
	$cmdR .= "&nbsp;&nbsp;&nbsp;";
	$cmdR .= "<a class=\"cmd1\" href=\"tabelleValIns.php?id=".reqVar('id')."&$sXSNQS\">nuovo valore</a>"; 
}

testaHtml('Gestione applicazione',$msgPag,'gest');
echo getHtmlForm();
echo getHtmlHidden('azione','reload');
echo getHtmlHidden('xsn',XSN);
echo getHtmlHidden('id');
echo getHtmlHidden('startoffset');
?>
<script type="text/javascript">
function confElimina() {
	if (confirm("Confermi l'eliminazione della tabella ?")) {
		document.location.href = 'tabelleView.php?azione=elimina&id=<?=reqVar('id')?>&xsn=<?=XSN?>';
	}
}
</script>
<table class="cmd1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="left">
         <?=$cmdL1?>
      </td>
      <td class="cmd1" align="right">
         <?=$cmdR1?>
      </td>
   </tr>
</table>
<table class="tab1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="lab1" width='20%' align='left'>Tabella</td>
      <td class="txt1" width='80%' align='left' colspan='3'>
			<span style='font-family:lucida console,courier;'><?=$acRecDom['cod_tabella']?></span>
			<?=' - '.$acRecDom['descr']?>
		</td>
   </tr>
<?
if (!empty($acRecDom['nota'])) {
?>
   <tr>
      <td class="lab1" valign='top'>Nota</td>
      <td class="txt1" colspan='3' align='left'>
			<?=getHtmlViewNote($acRecDom['nota'])?>
		</td>
   </tr>
<?
}
?>
   <tr>
      <td class="lab1" valign='top'>Lista campi</td>
      <td class="txt1" colspan='3' align='left'>
			<?=getHtmlViewNote($acRecDom['lista_campi'])?>
		</td>
   </tr>
<?php 
if (true) {
?>
   <tr>
      <td  class='lab1'>File da importare</td>
      <td class='txt1' colspan='3'>
         <input type="file" name="imp_file" class="inp1" size='40'>
         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         <input type='radio' name='tipo_agg' value='accoda' class="txt1" checked>accoda
         <input type='radio' name='tipo_agg' value='aggiorna' class="txt1">aggiorna
         <input type='radio' name='tipo_agg' value='sostituisci' class="txt1">sostituisci
         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         <a href="javascript:document.frm1.azione.value='importa';document.frm1.submit();" class='cmd1'>importa</a>
      </td>
   </tr>
<?php 
}
?>
</table>
<table class="cmd1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="left">
         <?=$cmdL?>
      </td>
      <td class="cmd1" align="right">
         <?=$cmdR."&nbsp;&nbsp;&nbsp;".$cmdR1?>
      </td>
   </tr>
</table>
<?
	$aLabCampi = explode(",",$acRecDom['lista_campi']);
	$nCampi = (count($aLabCampi) > 9) ? 9 : count($aLabCampi);
?>
<table class="cmd1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="left">
			<?=$sFiltro?>
      </td>
      <td class="cmd1" align="right">
			<?=$sPaginaz?>
      </td>
   </tr>
</table>
<table class="tab1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="lab1" align='center' width='1%'>&nbsp;</td>
      <td class="lab1" align='center' width='2%'><?=$aLabCampi[0]?></td>
			<?
$wX = round(97/($nCampi-1));
for($kX=1; $kX < $nCampi; $kX++) {
?>
      <td class="lab1" align='center' width='<?=$wX?>%'><?=$kX.") ".$aLabCampi[$kX]?></td>
<?
}
?>
   </tr>
<? 
$clRF = 'txt2';
while($acRecVal = $objDB->fetch('selRecVal')) { 
	$clRF = ($clRF=='txt1')?'txt2':'txt1';	
?>
   <tr>
      <td class="<?=$clRF?>"><?php echo ($acRecVal['scaduto']=='S')?'X':'&nbsp;'?></td>
      <td class="<?=$clRF?>">
      	<a href='tabelleValView.php?id=<?=reqVar('id')?>&key=<?=urlencode($acRecVal['chiave'])."&$sXSNQS"?>' class="<?=$clRF?>"
      	 	style='font-family:lucida console,courier;'>
            <?
            echo $acRecVal['chiave'];
            ?>
         </a>
      </td>
<?
	for($kX=1; $kX < $nCampi; $kX++) {
		$ncX = "c".str_pad($kX,2,'0',STR_PAD_LEFT);
?>
      <td class="<?=$clRF?>">
      	<? echo $acRecVal[$ncX];?>
      </td>
<?
	}
?>
<? 
} ?>
</table>
<table class="cmd1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="right">
<?=$sPaginaz?>
      </td>
   </tr>
</table>
<?
echo "</form>\n";
codaHtml();
exit();

function eliminaDom() {
	global $objDB;
	$mess = '';
	$sql = "DELETE FROM rgl_tabelle_val WHERE id_tabella = ".reqVar('id');
	$objDB->query($sql);
	$sql = "DELETE FROM rgl_tabelle WHERE id_tabella = ".reqVar('id');
	$objDB->query($sql);
	header("Location: ".urlTorna("tabelle eliminato"));
	exit();
}
function importaDomVal() {
	global $objDB;
	$mess = '';
	if (!isset($_FILES['imp_file']['tmp_name']) or $_FILES['imp_file']['tmp_name'] == "") {
      return "Selezionare un file !<br>";
   }
   if (!$fhInp = fopen($_FILES['imp_file']['tmp_name'],'rb')) {
      return "Impossibile aprire file caricato !<br>";
   }
   $aInp = fgetcsv($fhInp,1024,";");
   $numCampi = count($aInp);
   $numRecInp = 1;
   $numRecCar = 0;
   $loadFilePath = RGL_FS_TEMP_DIR."/".uniqid();
   if (!$fh = fopen($loadFilePath,'w')) {
   	return "impossibile scrivere file temp. $loadFilePath";
   }
   $idDom = reqVar('id');
   while($aInp=fgetcsv($fhInp,1024,";")) {
      $numRecInp++;
      if (trim($aInp[0]) == '') {
         $mess .= "n. rec. $numRecInp - campo chiave vuoto - rec. scartato<br>";
         continue ;
      }
      $strCampi = '"'.$idDom.'"';
      for($k=0; $k<=12; $k++) {
         if (isset($aInp[$k])) {
            $strCampi .= ';"'.str_replace('"',"'",$aInp[$k]).'"';
         } else {
            $strCampi .= ';"";';
         }
      }
      fwrite($fh,$strCampi."\n");
   }
   fclose($fh);
   if (reqVar('tipo_agg') == 'sostituisci') {
      $sql = "DELETE FROM rgl_tabelle_val WHERE id_tabella = ".$idDom;
      $objDB->query($sql);
   }
   if (reqVar('tipo_agg') == 'accoda') {
   	$sIgnRep = 'IGNORE';
   } else {
     	$sIgnRep = 'REPLACE';
   }	     
   if (stripos(rglVx($_ENV,'OS'),'WINDOWS')!==false) {
   	$loadFilePath = str_replace("/","\\",$loadFilePath);
   }       
   $sql = "LOAD DATA LOCAL INFILE '".addslashes($loadFilePath)."' $sIgnRep INTO TABLE rgl_tabelle_val "
    	." FIELDS TERMINATED BY ';' ENCLOSED BY '\"' LINES TERMINATED BY '\\n' "
    	." (id_tabella, chiave, c01,c02,c03,c04,c05,c06,c07,c08,c09,c10,c11,c12) ";
   $objDB->query($sql);
   $numRecCar += $objDB->affectedRec();
   $mess .= "-- importazione eseguita - modalita': ".reqVar('tipo_agg')." -- <br>";
   $mess .= "letti n. $numRecInp rec.<br>";
   $mess .= "caricati n. $numRecCar rec.<br>";
   return $mess;	
}